package com.itcoon.cloud.framework.utils;

import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SpringReflectionUtils {


    /**
     * 获取某个对象的属性值，包括父类
     * @param target
     * @param fieldName
     * @return
     */
    public static Object getField(Object target, String fieldName){
        Assert.notNull(target, "target must be not null.");
        Class<?> targetType = target.getClass();
        Field field = ReflectionUtils.findField(targetType, fieldName);
        if(field == null){
            throw new IllegalArgumentException("can not find field#" + fieldName + " in enum#"+targetType.getSimpleName());
        }
        ReflectionUtils.makeAccessible(field);
        return ReflectionUtils.getField(field, target);
    }

    /**
     * 查找并获取方法的结果
     * @param target
     * @param methodName
     * @param parameterTypes
     * @param args
     * @return
     */
    public static Object getMethodValue(Object target, String methodName,Class<?>[] parameterTypes, Object[] args){
        Assert.notNull(target, "target must not be null.");
        Method method;
        if(parameterTypes == null || parameterTypes.length == 0){
            method = ReflectionUtils.findMethod(target.getClass(), methodName);
            return ReflectionUtils.invokeMethod(method, target);
        }
        method = ReflectionUtils.findMethod(target.getClass(), methodName, parameterTypes);
        return ReflectionUtils.invokeMethod(method, target, args);
    }
}
